using System;
using BruteForce.Characters;
using BruteForce.GameObjects;
using BruteForce.NewManagers;
using BruteForce.Screens.PlayingScreen.Panels;
using BruteForce.UserInterface.Abstracts;
using BruteForce.UserInterface.UIControls;
using BruteForce.Utilities;
using Bruteforce.UserInterface.UIControls;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;

namespace BruteForce.Screens.CreateNewCharacterScreen {

    public class CreateNewCharacterPanel : AbstractPanel {
        public Button DefenderButton;
        public Button ArcherButton;
        public Button BomberButton;
        public Slider LifeSlider;
        public Slider LightSlider;
        public Slider PowerSlider;
        public Slider SpeedSlider;
        public CharacterType ChosenCharacter = CharacterType.Defender;
        public CreateNewCharacterPanel()
            : base("CreateNewCharacterPanel") {
            //var MenuItemName = "Player\n"+"number";
            //var diffBetweenLines = Draws.CalculateWordSizeNormalFont(MenuItemName);
            //var screenBounds = CalculteCenteredRectangle(panelRectangle, (int)diffBetweenLines.X, (int)Draws.NormalFontSize.Y * 2);
            //Label abstractMenuItem = new Label(MenuItemName, new Rectangle(screenBounds.X, screenBounds.Y, (int)diffBetweenLines.X, (int)diffBetweenLines.Y));
            //AddUIControl(abstractMenuItem);

            /*
            var screenBounds = panelRectangle;
            var Name = "Shooter";
            var img = GameLoop.TileShooter;
            var imgSuroundingRectangle = img.Bounds;
            Image abstractMenuItem = new Image(img, Name, new Rectangle(screenBounds.X, screenBounds.Y,imgSuroundingRectangle.Width,imgSuroundingRectangle.Height));
            AddUIControl(abstractMenuItem);
             * */
        }

        public static void LoadContent(ContentManager content) {
        }


        public override void Update(GameTime gameTime) {
            foreach (AbstractUIControl uiControl in Children) {
                uiControl.Update();
            }
        }

        public override void Draw(GameTime gameTime, SpriteBatch spriteBatch) {
            spriteBatch.End();
            spriteBatch.Begin(SpriteSortMode.FrontToBack, BlendState.Opaque, SamplerState.LinearWrap,
                              DepthStencilState.Default, RasterizerState.CullNone);
            spriteBatch.Draw(UIControlManager.Instance.BlackStoneTexture, new Vector2(Bounds.X, Bounds.Y), Bounds,
                             Color.White, 0, Vector2.Zero, 1, SpriteEffects.None, 0);
            spriteBatch.End();
            spriteBatch.Begin();
            Draws.DrawBorder(Bounds, new Color(91, 91, 91), 2);
            foreach (AbstractUIControl uiControl in Children) {
                uiControl.Draw(gameTime);
            }
        }


        public override void AfterLayout() {
            Texture2D image = UIControlManager.Instance.CreateAndPlaceButtonTexture;
            Texture2D image2 = UIControlManager.Instance.CreateAndPlacePressedButtonTexture;
            var dynamicButton = new DynamicButton(image,image2, "Create Button",
                                              new Rectangle((Bounds.Width - image.Width) / 2,
                                                            (Bounds.Height - image.Height) - 10, image.Width,
                                                            image.Height), IsThereResources);
            dynamicButton.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            dynamicButton.OnClick += (() => ScreenManager.Instance.CloseNewCharacterScreen(this));
            AddUIControl(dynamicButton);


            //cancel button
            image = UIControlManager.Instance.CancelButtonTexture;
            var abstractMenuItem = new Button(image, "Cancel Button",
                                              new Rectangle((Bounds.Width - image.Width) ,
                                                            (Bounds.Height - image.Height) - 10, image.Width,
                                                            image.Height));
            abstractMenuItem.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            abstractMenuItem.OnClick += (() => ScreenManager.Instance.CancelScreenCreatNewCharacter());
            AddUIControl(abstractMenuItem);


            //create "Resources Status :" label
            string labelText = "Life :";
            Vector2 diffBetweenLines = Draws.CalculateWordSizeNormalFont(labelText);

            //***********************************************************************calculating the middle of the panel - taking account of all the following UI controls
            const int spaceBetweenUIControls = 10;
            Rectangle centerLocation = CalculteCenteredRectangle(Bounds,
                                                                 (UIControlManager.Instance.SliderBackgroundTexture.
                                                                      Bounds.
                                                                      Width + spaceBetweenUIControls +
                                                                  (int)diffBetweenLines.X),
                                                                 ((int)
                                                                  (MathHelper.Max(
                                                                      UIControlManager.Instance.SliderBackgroundTexture.
                                                                          Bounds.
                                                                          Height, diffBetweenLines.Y)) * 4) +
                                                                 spaceBetweenUIControls * 4);
            int xPostionSliders = centerLocation.X + spaceBetweenUIControls + (int)diffBetweenLines.X;
            int yDiffBetweenControls = 80;
//                (int)
//                (MathHelper.Max(UIControlManager.Instance.SliderBackgroundTexture.Bounds.Height, diffBetweenLines.Y)) +
//                spaceBetweenUIControls;





            //************************************************************************



//            //labelText = "Life :" + it's slider
//            var label = new Label(labelText, labelText,
//                                  new Rectangle(centerLocation.X, centerLocation.Y, (int)diffBetweenLines.X,
//                                                (int)diffBetweenLines.Y));
//            label.SetOffset(new Vector2(Bounds.X, Bounds.Y));
//            AddUIControl(label);


            int hight =  centerLocation.Height;

            var neededresources = new InteractiveLabel("", "",
                 new Rectangle(xPostionSliders + UIControlManager.Instance.SliderBackgroundTexture.Width + 5 * spaceBetweenUIControls,
                     hight, 20, 20), GetNeededRecourcesStr);

            neededresources.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            neededresources.SetLabelTextColor(Color.White);
            AddUIControl(neededresources);



            var resources = new InteractiveLabel("","",
                 new Rectangle(xPostionSliders + UIControlManager.Instance.SliderBackgroundTexture.Width + 30*spaceBetweenUIControls,
                     hight, 20, 20), GetResources);

            resources.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            resources.SetLabelTextColor(Color.DarkGreen);
            AddUIControl(resources);



            neededresources = new InteractiveLabel("", "", new Rectangle(spaceBetweenUIControls + +5 * spaceBetweenUIControls, hight, 20, 20), GetCostOfCharacterInfo);
            neededresources.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            neededresources.SetLabelTextColor(Color.White);
            AddUIControl(neededresources);


            // life img

            var scale = 6;
            var imgHight = UIControlManager.Instance.LifeTexture.Height/scale;
            var imgWidth = UIControlManager.Instance.LifeTexture.Width /scale;


            var img = new Image(UIControlManager.Instance.LifeTexture, "",
                                new Rectangle(centerLocation.X - imgWidth, centerLocation.Y, imgWidth,
                                             imgHight));
            img.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            AddUIControl(img);


            LifeSlider = new Slider(UIControlManager.Instance.SliderBackgroundTexture,
                                    UIControlManager.Instance.SliderScrollBarTexture,
                                    "Life Slider",
                                    new Rectangle(xPostionSliders, centerLocation.Y,
                                                  UIControlManager.Instance.SliderBackgroundTexture.Width,
                                                  UIControlManager.Instance.SliderBackgroundTexture.Height),
                                    1, Color.White, ShowLifeSlider,GetMaxLifeSlider);
            LifeSlider.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            AddUIControl(LifeSlider);

//            //labelText = "Light :" + it's slider
//            labelText = "Light :";
//            var label = new Label(labelText, labelText,
//                              new Rectangle(centerLocation.X, centerLocation.Y + yDiffBetweenControls,
//                                            (int)diffBetweenLines.X,
//                                            (int)diffBetweenLines.Y));
//            label.SetOffset(new Vector2(Bounds.X, Bounds.Y));
//            AddUIControl(label);

            scale = 2;
            imgHight = UIControlManager.Instance.LightTexture.Height / scale;
            imgWidth = UIControlManager.Instance.LightTexture.Width / scale;


            img = new Image(UIControlManager.Instance.LightTexture, "",
                                new Rectangle(centerLocation.X - imgWidth, centerLocation.Y + yDiffBetweenControls,
                                    imgWidth,
                                              imgHight));
            img.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            AddUIControl(img);

            LightSlider = new Slider(UIControlManager.Instance.SliderBackgroundTexture,
                                     UIControlManager.Instance.SliderScrollBarTexture,
                                     "Light Slider",
                                     new Rectangle(xPostionSliders,
                                                   centerLocation.Y + yDiffBetweenControls,
                                                   UIControlManager.Instance.SliderBackgroundTexture.Width,
                                                   UIControlManager.Instance.SliderBackgroundTexture.Height),
                                     1, Color.White, ShowLightSlider,GetMaxLightSlider);
            LightSlider.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            AddUIControl(LightSlider);


//            //labelText = "Speed :" + it's slider
//            labelText = "Speed :";
//            label = new Label(labelText, labelText,
//                              new Rectangle(centerLocation.X, centerLocation.Y + yDiffBetweenControls * 2,
//                                            (int)diffBetweenLines.X,
//                                            (int)diffBetweenLines.Y));
//            label.SetOffset(new Vector2(Bounds.X, Bounds.Y));
//            AddUIControl(label);


            scale = 2;
            imgHight = UIControlManager.Instance.SpeedTexture.Height / scale;
            imgWidth = UIControlManager.Instance.SpeedTexture.Width / scale;


            img = new Image(UIControlManager.Instance.SpeedTexture, "",
                                new Rectangle(centerLocation.X - imgWidth + 30, centerLocation.Y + yDiffBetweenControls * 2,
                                    imgWidth,
                                           imgHight));
            img.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            AddUIControl(img);


            SpeedSlider = new Slider(UIControlManager.Instance.SliderBackgroundTexture,
                                     UIControlManager.Instance.SliderScrollBarTexture,
                                     "Speed Slider",
                                     new Rectangle(xPostionSliders,
                                                   centerLocation.Y + yDiffBetweenControls * 2,
                                                   UIControlManager.Instance.SliderBackgroundTexture.Width,
                                                   UIControlManager.Instance.SliderBackgroundTexture.Height),
                                     1, Color.White, ShowSpeedSlider,GetMaxSpeedSlider);
            SpeedSlider.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            AddUIControl(SpeedSlider);


//            //labelText = "Life :" + it's slider
//            labelText = "Power :";
//            label = new Label(labelText, labelText,
//                              new Rectangle(centerLocation.X, centerLocation.Y + yDiffBetweenControls * 3,
//                                            (int)diffBetweenLines.X,
//                                            (int)diffBetweenLines.Y));
//            label.SetOffset(new Vector2(Bounds.X, Bounds.Y));
//            AddUIControl(label);

            scale = 2;
            imgHight = UIControlManager.Instance.PowerTexture.Height / scale;
            imgWidth = UIControlManager.Instance.PowerTexture.Width / scale;

            img = new Image(UIControlManager.Instance.PowerTexture, "",
                                new Rectangle(centerLocation.X - imgWidth, centerLocation.Y + yDiffBetweenControls * 3,
                                    imgWidth,imgHight));
            img.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            AddUIControl(img);


            PowerSlider = new Slider(UIControlManager.Instance.SliderBackgroundTexture,
                                     UIControlManager.Instance.SliderScrollBarTexture,
                                     "Power Slider",
                                     new Rectangle(xPostionSliders,
                                                   centerLocation.Y + yDiffBetweenControls * 3,
                                                   UIControlManager.Instance.SliderBackgroundTexture.Width,
                                                   UIControlManager.Instance.SliderBackgroundTexture.Height),
                                     1, Color.White, ShowPowerSlider,GetMaxPowerSlider);
            PowerSlider.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            AddUIControl(PowerSlider);

            //*********************************Adding the characters chooser buttons*******************************//

            int diffBetweenPic = 10;


            //Defender
            image = PlayerManager.Instance.CurrentPlayer.Property.PlayerType == PlayerType.Human ? UIControlManager.Instance.HumanDefenderButtonTexture : UIControlManager.Instance.MonsterDefenderButtonTexture;
            centerLocation = CalculteCenteredRectangle(new Rectangle(0, 0, Bounds.Width, centerLocation.Y),
                                                       (image.Width + diffBetweenPic) * 3, image.Height);

            DefenderButton = new Button(image, "Defender",
                                              new Rectangle(centerLocation.X,
                                                            centerLocation.Y, image.Width,
                                                            image.Height));
            DefenderButton.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            DefenderButton.OnClick += (() => ChooseCharacter(CharacterType.Defender));
            AddUIControl(DefenderButton);


            //Bomber

            image = PlayerManager.Instance.CurrentPlayer.Property.PlayerType == PlayerType.Human ? UIControlManager.Instance.HumanBomberButtonTexture : UIControlManager.Instance.MonsterBomberButtonTexture;

            BomberButton = new Button(image, "Bomber",
                                              new Rectangle(centerLocation.X + image.Width + diffBetweenPic,
                                                            centerLocation.Y, image.Width,
                                                            image.Height));
            BomberButton.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            BomberButton.OnClick += (() => ChooseCharacter(CharacterType.Bomber));
            AddUIControl(BomberButton);



            //Archer

            image = PlayerManager.Instance.CurrentPlayer.Property.PlayerType == PlayerType.Human ? UIControlManager.Instance.HumanArcherButtonTexture : UIControlManager.Instance.MonsterArcherButtonTexture;
            ArcherButton = new Button(image, "Archer",
                                              new Rectangle(centerLocation.X + (image.Width + diffBetweenPic) * 2,
                                                            centerLocation.Y, image.Width,
                                                            image.Height));
            ArcherButton.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            ArcherButton.OnClick += (() => ChooseCharacter(CharacterType.Archer));
            AddUIControl(ArcherButton);


            
            ChooseCharacter(CharacterType.Defender);


        }

        private string GetCostOfCharacterInfo()
        {
            switch(ChosenCharacter)
            {
                case CharacterType.Archer:
                    return "One Life  = Two Food\n\n" +
                           "One Light = Three Iron\n\n" +
                           "One Speed = Two Speed Potion\n\n" +
                           "One Power = Two Iron\n\n";
                case CharacterType.Bomber:
                    return "One Life  = Five Food \n\n" +
                           "One Light = Ten Iron + 3 Food\n\n" +
                           "One Speed = One Speed Potion + Three Food\n\n" +
                           "One Power = Five Iron\n\n";
                case CharacterType.Defender:
                    return "One Life  =  One Food + Two Iron\n\n" +
                           "One Speed =  Five Speed Potion\n\n";
            }
            return "";
        }

        public Resources GetPlayerRecourcesMinusSliders()
        {
            var neededRecources = GetNeededRecources();
            var diffRecources = new Resources(PlayerManager.Instance.CurrentPlayer.Property.CurrentResources);
            diffRecources.RemoveResources(neededRecources);
            return diffRecources;

        }

        public Resources GetNeededRecources()
        {
            var sliderRecources = GetSliderRecources();
            var neededRecources = GetmaxSlider(sliderRecources);
            return neededRecources;
        }

        public String GetNeededRecourcesStr()
        {
            return "Needed Resources : \n" + GetNeededRecources().ToString();
        }

        private void CreateInteractiveLabel(Func<string> method, string labelText, Rectangle overallRectangle)
        {
            var InteractiveLabel = new InteractiveLabel("InteractiveLabel", labelText, overallRectangle, method);
            InteractiveLabel.SetOffset(new Vector2(Bounds.X, Bounds.Y));
            InteractiveLabel.SetLabelTextColor(Color.Black);
            AddUIControl(InteractiveLabel);
        }


        private void ChooseCharacter(CharacterType characterType)
        {

            //reset the labels

            foreach (var uiControl in _uiControls)
            {
                if(uiControl is Slider)
                {
                    ((Slider)uiControl).Reset();
                }
            }

            ChosenCharacter = characterType;
            if (PlayerManager.Instance.CurrentPlayer.Property.PlayerType == PlayerType.Human)
            {
                DefenderButton.Image = UIControlManager.Instance.HumanDefenderButtonTexture;
                ArcherButton.Image = UIControlManager.Instance.HumanArcherButtonTexture;
                BomberButton.Image = UIControlManager.Instance.HumanBomberButtonTexture;
                switch (characterType)
                {
                    case CharacterType.Defender:
                        DefenderButton.Image = UIControlManager.Instance.HumanDefenderPressedButtonTexture;
                        PowerSlider.SetMinValue(0);
                        LightSlider.SetMinValue(0);
                        break;
                    case CharacterType.Archer:
                        ArcherButton.Image = UIControlManager.Instance.HumanArcherPressedButtonTexture;
                        PowerSlider.SetMinValue(1);
                        LightSlider.SetMinValue(1);
                        break;
                    case CharacterType.Bomber:
                        BomberButton.Image = UIControlManager.Instance.HumanBomberPressedButtonTexture;
                        PowerSlider.SetMinValue(1);
                        LightSlider.SetMinValue(1);
                        break;
                }
            }
            else if (PlayerManager.Instance.CurrentPlayer.Property.PlayerType == PlayerType.Monster)
            {
                DefenderButton.Image = UIControlManager.Instance.MonsterDefenderButtonTexture;
                ArcherButton.Image = UIControlManager.Instance.MonsterArcherButtonTexture;
                BomberButton.Image = UIControlManager.Instance.MonsterBomberButtonTexture;
                switch (characterType)
                {
                    case CharacterType.Defender:
                        DefenderButton.Image = UIControlManager.Instance.MonsterDefenderPressedButtonTexture;
                        PowerSlider.SetMinValue(0);
                        LightSlider.SetMinValue(0);
                        break;
                    case CharacterType.Archer:
                        ArcherButton.Image = UIControlManager.Instance.MonsterArcherPressedButtonTexture;
                        PowerSlider.SetMinValue(1);
                        LightSlider.SetMinValue(1);
                        break;
                    case CharacterType.Bomber:
                        BomberButton.Image = UIControlManager.Instance.MonsterBomberPressedButtonTexture;
                        PowerSlider.SetMinValue(1);
                        LightSlider.SetMinValue(1);
                        break;
                }
            }

        }

        #region delegated functions

        public Boolean ShowLifeSlider()
        {
            return true;

        }

       public Boolean ShowLightSlider()
       {
           return IsChosenCharacter(CharacterType.Archer) || IsChosenCharacter(CharacterType.Bomber);

       }

         public Boolean ShowSpeedSlider()
         {
             return true;

         }


        public Boolean ShowPowerSlider()
        {
            return IsChosenCharacter(CharacterType.Archer) || IsChosenCharacter(CharacterType.Bomber);
        }

        public Resources GetmaxSlider(Resources resources)
        {
            return CharacterCreationLogic.GetNeededResources(ChosenCharacter ,resources);
        }

        public Resources GetMaxAggregatedSliderValue()
        {

            var ans = GetmaxSlider(new Resources(1, 0, 0, 0));
            ans.AddResources(GetmaxSlider(new Resources(0, 1, 0, 0)));
            ans.AddResources(GetmaxSlider(new Resources(0, 0, 1, 0)));
            ans.AddResources(GetmaxSlider(new Resources(0, 0, 0, 1)));
            return ans;
        }

//        public Resources getMinResources(Resources FirstResources ,Resources SecondResources)
//        {
//            var resources = new Resources(
//                Math.Min(FirstResources.Light, SecondResources.Light),
//                Math.Min(FirstResources.Power, SecondResources.Power),
//                Math.Min(FirstResources.Light, SecondResources.Life),
//                Math.Min(FirstResources.Light, SecondResources.Life));
//
//            return null;
//        }


        private int GetMaxRatio(Resources maxRes)
        {
            var currentRes = new Resources(PlayerManager.Instance.CurrentPlayer.Property.CurrentResources);

            int ans = int.MaxValue;

            if (maxRes.Life == 0)
                currentRes.RemoveResources(GetmaxSlider(new Resources(0, 0, 1, 0)));
            if(maxRes.Power == 0)
                currentRes.RemoveResources(GetmaxSlider(new Resources(0, 1, 0, 0)));
            if (maxRes.Light == 0)
                currentRes.RemoveResources(GetmaxSlider(new Resources(1, 0, 0, 0)));
            if (maxRes.Power == 0)
                currentRes.RemoveResources(GetmaxSlider(new Resources(1, 0, 0, 0)));


            if (maxRes.Life != 0)
                ans = (int)((Math.Floor((float)currentRes.Life/((float)maxRes.Life))));

            if (maxRes.Light != 0)
                ans = Math.Min(ans, (int)(Math.Floor((float)currentRes.Light/(float)maxRes.Light)));
            if (maxRes.Power != 0)
                ans = Math.Min(ans, (int)(Math.Floor((float)currentRes.Power/(float)maxRes.Power)));
            if (maxRes.Speed != 0)
                ans = Math.Min(ans, (int)(Math.Floor((float)currentRes.Speed/(float)maxRes.Speed)));
            return ans + 1;
        }

        public int GetMaxLifeSlider()
        {
            var maxRes = GetmaxSlider(new Resources(0, 0, 1, 0));
            var ans = GetMaxRatio(maxRes);
            return ans;
        }



        public int GetMaxLightSlider()
        {
//            return PlayerManager.Instance.CurrentPlayer.Property.CurrentResources.Light / GetmaxSlider(new Resources(1, 0, 0, 0)).Light;


            var maxRes = GetmaxSlider(new Resources(1, 0, 0, 0));
            var ans = GetMaxRatio(maxRes);
            return ans;
        }

        public int GetMaxPowerSlider()
        {
//            return PlayerManager.Instance.CurrentPlayer.Property.CurrentResources.Power / GetmaxSlider(new Resources(0, 1,0, 0)).Power;


            var maxRes = GetmaxSlider(new Resources(0, 1,0, 0));
            var ans = GetMaxRatio(maxRes);
            return ans;
        }

        public int GetMaxSpeedSlider()
        {

            var maxRes = GetmaxSlider(new Resources(0, 0, 0, 1));
            var ans = GetMaxRatio(maxRes);
            return ans;
            
//            return PlayerManager.Instance.CurrentPlayer.Property.CurrentResources.Speed / GetmaxSlider(new Resources(0, 0, 0, 1)).Speed;
        }

        public String GetResources()
        {
            var diffResources = GetPlayerRecourcesMinusSliders();
            var ans = diffResources.ToString();
            if (!IsEnoughResources(diffResources))
            {
                ans += "\nNot Enough Resources";
            }
            return "Left Resources : \n"+ans;
        }

        public Boolean IsThereResources()
        {
            var neededRecources = GetPlayerRecourcesMinusSliders();
            if (neededRecources.Life < 0 || neededRecources.Light < 0 || neededRecources.Power < 0 || neededRecources.Speed < 0)
                return false;
            return true;
        }

        public Boolean IsEnoughResources(Resources neededRecources)
        {
            if (neededRecources.Life < 0 || neededRecources.Light < 0 || neededRecources.Power < 0 || neededRecources.Speed < 0)
                return false;
            return true;
        }

        public Resources GetSliderRecources()
        {
            return new Resources(LightSlider.GetSliderValue, PowerSlider.GetSliderValue,
                                 LifeSlider.GetSliderValue, SpeedSlider.GetSliderValue);
        }

        #endregion

                private Boolean IsChosenCharacter(CharacterType characterType)
                {
                    return characterType == ChosenCharacter;
                }


     
    }
}